package com.roy.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/2
 * @description:
 **/

public class BioServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务启动完成");
        while (true) {
            new Thread(()->{}).start();
            //BIO每次会在这个地方阻塞住，只到有请求进来。
            final Socket socket = serverSocket.accept();
            System.out.println("有请求进来了。");
            //通过inputStream解析客户端传过来的消息
            final InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            //连接建立后，如果当前线程暂时没有数据可读，则线程就阻塞在 Read 操作上，造成线程资源浪费
//            while (true) {
                len = inputStream.read(buffer);
//                if (len == -1) {
//                    break;
//                }
                System.out.println("收到消息：" + new String(buffer, 0, len));
//              buffer = new byte[1024];
//            }
            //通过outputStream给客户端返回响应
            final OutputStream outputStream = socket.getOutputStream();
            outputStream.write(("你的消息 ：" + new String(buffer) + " 收到了。").getBytes());
            outputStream.flush();
            System.out.println("返回消息响应。");

            inputStream.close();
            outputStream.close();
            socket.close();
        }
    }
}
